<template>
  <el-dialog title="编辑"  :close-on-click-modal="false" :visible.sync="show" 
  class="dialog_index dialog_banner site_fixed"
   :before-close="cancle">
    <el-form  v-loading="loading" class="product_import_export_form ">
      <el-tabs type="card" v-model="activeName">
          <el-tab-pane :label="item.site" :name="item.site"  v-for="item  in formList" :key="item.id">
            <el-form-item label="一级类型：">
              <el-select v-model="item.first_product_id"  :placeholder="'一级类型（必填项)'"     @change="(value)=>changeFirstType(value, item)">
                <el-option v-for="item in item.firstTypeList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级类型：">
              <el-select v-model="item.second_product_id"  filterable :placeholder="'二级类型（必填项)'"   @change="changeSecondType">
                <el-option v-for="item in item.secondTypeList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="进出口类型：">
              <el-radio-group v-model="item.import_export_type" @change="value => changeType(value)">
                <el-radio :label="1">Input&Output</el-radio>
                <el-radio :label="2">Male&Female</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="Input：" v-show="item.import_export_type === 1" >
              <el-input  :placeholder="'Input('+item.site+')（必填项)'" v-model="item.input_name"></el-input>
              <div class="upload_module">
                <el-upload class="upload-image" :action="actionUrl"  multiple
                :on-success="(response) => handleSuccess(response, 'input')"
                  :on-error="handleError" :before-upload="beforeUpload"
                :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type: 'input', imageheight: imgH, imagewidth: imgW}" >
                  <el-button size="small" type="primary" @click="closeDrawerDialog('input')">图库选择</el-button> 
                  <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  <div class="pop_container">
                    <el-image v-if="item.input_image" :src="utils.setCdnUrl() + item.input_image" class="pop_image"></el-image>
                  </div>
                </el-upload>
                <p>建议上传.png/.jpg/.jpeg格式，且尺寸为1:1，大小≤1M，每次只能上传一个</p>
              </div>

            </el-form-item>
            <el-form-item label="Output：" v-show="item.import_export_type === 1">
              <el-input  :placeholder="'Output('+item.site+')（必填项)'" v-model="item.output_name"></el-input>
              <div class="upload_module">
                <el-upload class="upload-image" :action="actionUrl"  multiple
                :on-success="(response) => handleSuccess(response, 'output')"
                  :on-error="handleError" :before-upload="beforeUpload"
                :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type: 'output', imageheight: imgH, imagewidth: imgW}" >
                  <el-button size="small" type="primary" @click="closeDrawerDialog('output')">图库选择</el-button> 
                  <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  <div class="pop_container">
                    <el-image v-if="item.output_image" :src="utils.setCdnUrl() +item.output_image" class="pop_image"></el-image>
                  </div>
                </el-upload>
                <p>建议上传.png/.jpg/.jpeg格式，且尺寸为1:1，大小≤1M，每次只能上传一个</p>
              </div>

            </el-form-item>
            <el-form-item label="Male：" v-show="item.import_export_type === 2">
              <el-input  :placeholder="'Male('+item.site+')（必填项)'" v-model="item.male_name"></el-input>
              <div class="upload_module">
                <el-upload class="upload-image" :action="actionUrl"  multiple
                :on-success="(response) => handleSuccess(response, 'male')"
                  :on-error="handleError" :before-upload="beforeUpload"
                :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type: 'male', imageheight: imgH, imagewidth: imgW}" >
                  <el-button size="small" type="primary" @click="closeDrawerDialog('male')">图库选择</el-button> 
                  <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  <div class="pop_container">
                    <el-image v-if="item.male_image" :src="utils.setCdnUrl()  + item.male_image" class="pop_image"></el-image>
                  </div>
                </el-upload>
                <p>建议上传.png/.jpg/.jpeg格式，且尺寸为1:1，大小≤1M，每次只能上传一个</p>
              </div>

            </el-form-item>
            <el-form-item label="Female：" v-show="item.import_export_type === 2">
              <el-input  :placeholder="'Female('+item.site+')（必填项)'" v-model="item.female_name"></el-input>
              <div class="upload_module">
                <el-upload class="upload-image" :action="actionUrl"  multiple
                :on-success="(response) => handleSuccess(response, 'female')"
                  :on-error="handleError" :before-upload="beforeUpload"
                :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type: 'female', imageheight: imgH, imagewidth: imgW}" >
                  <el-button size="small" type="primary" @click="closeDrawerDialog('female')">图库选择</el-button> 
                  <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  <div class="pop_container">
                    <el-image v-if="item.female_image" :src="utils.setCdnUrl()+ item.female_image" class="pop_image"></el-image>
                  </div>
                </el-upload>
                <p>建议上传.png/.jpg/.jpeg格式，且尺寸为1:1，大小≤1M，每次只能上传一个</p>
              </div>

            </el-form-item>
          </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm" :loading="isSubmit">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="imageType" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

  </el-dialog>
</template>

<script>
import { editGet, editPost } from '@/api/product/productImportExport.js'
import { allFirstTypeList, allSecondTypeList } from '@/api/product/productType.js'
import Drawer  from '@/components/Gallery/index.vue' 

export default {
  props: {
    show: Boolean,
    closeAddDialog:Function,
    id: Number
  },
  data() {
    return {
      formList: [],
      loading: false,
      activeName: 'us',
      firstTypeList: [], //一级类型下拉框
      secondTypeList: [], //二级类型下拉框
      actionUrl: '/api/api/general/upload',
      imageType: "",  //类别 取值：input、output、male、female
      showDrawer: false,//图库选择模块的显示
      imgW: '',
      imgH: '',
      isSubmit: false
    }
  },
  components: { Drawer },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.getData()
      }
    }
  },
  methods:{
    getAllFirstTypeList() { // 获取所有站点一级类型
      allFirstTypeList().then(res=>{
        let data = res.data
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          list[i].firstTypeList = data[list[i].site_id]
        }
        this.formList = list
        this.getAllSecondTypeList(list[0], list[0].first_product_id)
      })
    },
    getAllSecondTypeList(item, value) {// 获取所有站点二级类型
      let firstTypeList = item.firstTypeList
      let product_ids= []  //根据当前一级类型获取二级类型
      for(let i = 0; i < firstTypeList.length; i++) {
        if(firstTypeList[i].product_id == value){
          product_ids = firstTypeList[i].product_ids
        }
      }
      let params = {
        product_ids: product_ids
      }
      allSecondTypeList(params).then(res=>{
        let data = res.data
        let list = this.formList 
        for(let i = 0; i < list.length; i++){
          list[i].secondTypeList = data[list[i].site_id]
        }
        this.formList = list
      })
    },
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer

      if(this.showDrawer) { //展示图库
        this.imageType = data
      } else { // 选择图片
        if(data && data.filePathNameHttp )  { 
          for(let i =0; i< this.formList.length; i++){
            this.formList[i][this.imageType+"_image"] = data.filePathName
          } 
        }
      }
    },
    /**
     * type： 代表类别 取值：input、output、male、female
     */
    handleSuccess(response, type){ //上传成功
      for(let i =0; i< this.formList.length; i++){
        this.formList[i][type+'_image'] = response.data.filePathName
      }
      this.$message.success('上传图片成功')   
    },
    handleError(){
      this.$message.error('上传图片失败')   
    },
    beforeUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg'){
        this.$message.error("仅支持.jpg/.jpeg/png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width ==  img.height ;
          valid ? resolve() : reject();
          that.imgW = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        return file
      })
      return isSize
    },
    changeType (value){
      let list = this.formList
      for(let i = 0; i < list.length; i++){
        list[i].import_export_type = value
      }
      this.formList = JSON.parse(JSON.stringify(list))
    },
    changeSecondType (value) {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].second_product_id = value
        for(let j = 0; j < list[i].secondTypeList.length; j++ ){
          let item = list[i].secondTypeList[j]
          if(list[i].second_product_id == item.product_id){
            list[i].second_type = item.value
          }
        }
      }
      this.formList = list
    },
    clearFirstType () {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].second_type = ""
        list[i].secondTypeList = []
        list[i].first_type = ""
      }
    },
    //一级类型改变时同步所有站点，并获取二级类型的下拉框数据
    changeFirstType (value, item) {
      let list = this.formList //所有站点一级类型赋值
      for (let i = 0; i <  list.length; i++){
        list[i].first_product_id = value
        list[i].second_product_id = ''
        list[i].second_type = ''
        list[i].secondTypeList = []
        for(let j = 0; j < list[i].firstTypeList.length; j++ ){
          let item = list[i].firstTypeList[j]
          if(value == item.product_id){
            list[i].first_type = item.value
          }
        }
      }
      this.formList = list
      this.getAllSecondTypeList(item, value)  //获取二级类型的参数  

    },
    getData () {
      let params = {
        product_id: this.id
      }
      editGet(params).then(res => {
        if (res.status == 200) {
          let data = res.data
          for(let i = 0; i < data.length; i++  ) {
            data[i].firstTypeList = []
            data[i].secondTypeList = []
            if (i == 0 ){
              this.activeName = data[i].site
            }
          }
          if(data[0].import_export_type == 1) {
            this.image = {
              'input': data[0].httpInputImage,
              'output': data[0].httpOutputImage,
              'male': '',
              'female': ''
            }
          } else {
            this.image = {
              'input': '',
              'output': '',
              'male': data[0].httpMaleImage,
              'female': data[0].httpFemaleImage
            }
          }
        
          this.formList= data
          this.loading = false
          this.getAllFirstTypeList()

        }
      })
    },
    submitForm(){
      let status = this.validateForm()
      if(status){
        this.submitData()
      }
    },
    validateForm () {
      let list = this.formList
      let status = true
      for ( let i = 0; i < list.length; i++ ){
        if (list[i].first_product_id === '') {
          this.$message.error('站点' + list[i].site + '一级类型为必填项')
          status = false
          break
        }
        if (list[i].second_product_id === '') {
          this.$message.error('站点' + list[i].site + '二级类型为必填项')
          status = false
          break
        }
        if(list[i].import_export_type == 1) {
          if (list[i].input_name === '') {
            this.$message.error('站点' + list[i].site + 'Input为必填项')
            status = false
            break
          }
          if (list[i].output_name === '') {
            this.$message.error('站点' + list[i].site + 'Output为必填项')
            status = false
            break
          }
           if (list[i].input_image === '') {
            this.$message.error('站点' + list[i].site + 'Input图片为必填项')
            status = false
            break
          }
          if (list[i].output_image === '') {
            this.$message.error('站点' + list[i].site + 'Output图片为必填项')
            status = false
            break
          }
        } else {
           if (list[i].male_name === '') {
            this.$message.error('站点' + list[i].site + 'Male为必填项')
            status = false
            break
          }
          if (list[i].female_name === '') {
            this.$message.error('站点' + list[i].site + 'Female为必填项')
            status = false
            break
          }
          if (list[i].male_image === '') {
            this.$message.error('站点' + list[i].site + 'Male图片为必填项')
            status = false
            break
          }
          if (list[i].female_image === '') {
            this.$message.error('站点' + list[i].site + 'Female图片为必填项')
            status = false
            break
          }
        }
         
      
        
      }
      return status
    },
    submitData(){
      this.isSubmit = true
      let list = JSON.parse(JSON.stringify(this.formList))
      for(let i = 0; i <list.length; i++){
        delete list[i].firstTypeList
        delete list[i].secondTypeList
        if(list[i].import_export_type == 1) {
          list[i].male_name = ''
          list[i].male_image = ''
          list[i].female_image = ''
          list[i].female_name = ''
        } else if(list[i].import_export_type == 2) {
          list[i].input_name = ''
          list[i].input_image = ''
          list[i].output_image = ''
          list[i].output_name = ''
        }
      }
      let params = {
        data: JSON.stringify(list)
      }
      editPost(params).then(res=>{
       if(res.state == 1) {
         this.$message.success('编辑成功')
         this.cancle()
       }
       this.isSubmit = false
      })
    },
    cancle(){
      this.$emit('closeDialog')
      this.image = {
        'input': '',
        'output': '',
        'male': '',
        'female': ''
      }
    },
  }
}
</script>

<style lang="scss">

</style>